package com.yc.study.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yc.study.entity.Course;
import com.yc.study.entity.CourseOrder;
import com.yc.study.entity.User;
import com.yc.study.service.ICourseOrderService;
import com.yc.study.service.ICourseService;
import com.yc.study.service.IUserService;
import com.yc.study.vo.CourseVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.web.bind.annotation.*;

import java.security.Principal;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 前端控制器
 *
 * @author 王妍
 * @since 2022-02-20
 */
@RestController
@RequestMapping("/study/course")
public class CourseController {

  @Autowired private ICourseService courseService;

  @Autowired private IUserService userService;

  @Autowired private ICourseOrderService courseOrderService;
  /** 创建课程 */
  @PostMapping
  public CourseVo createCourse(Principal principal,@RequestBody CourseVo courseInfo) {
    String username = principal.getName();
    courseService.save(courseInfo, username);
    return courseInfo;
  }

  @GetMapping("/page")
  public Page<CourseVo> getPage(Principal principal,Page<CourseVo> courseVoPage, CourseVo course) {
    final String username = principal.getName();
    final User user = userService.loadUserByUserName(username);
    course.setTeacherId(user.getId());
    return courseService.loadPage(courseVoPage, course);
  }

  @DeleteMapping
  public void delete(@RequestBody Long[] courseIds) {
    courseService.removeBatchByIds(Arrays.asList(courseIds));
  }

  @GetMapping
  public List<CourseVo> list() {
    List<Course> courseList = courseService.list();
    List<CourseVo> courseVoList = courseList.stream().map(course -> {
      CourseVo courseVo = new CourseVo();
      BeanUtils.copyProperties(course,courseVo);
      Long teacherId = course.getTeacherId();
      if(teacherId!=null){
        User byId = userService.getById(teacherId);
        Optional.ofNullable(byId).ifPresent(user -> courseVo.setTeacherName(user.getNickname()));
      }
      return  courseVo;
    }).collect(Collectors.toList());
    return courseVoList;
  }

  @GetMapping("{courseId}")
  public CourseVo getInfo(@PathVariable Long courseId) {
    final CourseVo courseVo = new CourseVo();
    final Course course = courseService.getById(courseId);
    BeanUtils.copyProperties(course, courseVo);
    final User teacher = userService.getById(courseVo.getTeacherId());
    courseVo.setTeacherName(teacher.getNickname());
    return courseVo;
  }

  @GetMapping("subscribed")
  public Page<CourseVo> getSubscribed(
      Principal principal, Page<CourseVo> coursePage, CourseVo course) {
    User user =
        Optional.ofNullable(userService.loadUserByUserName(principal.getName()))
            .orElseThrow(() -> new UsernameNotFoundException("用户名不存在！！"));
    return courseService.getSubscribed(user.getId(), coursePage, course);
  }

  @GetMapping("noSubscribed")
  public Page<CourseVo> getNoSubscribed(
      Principal principal, Page<CourseVo> coursePage, CourseVo course) {
    User user =
        Optional.ofNullable(userService.loadUserByUserName(principal.getName()))
            .orElseThrow(() -> new UsernameNotFoundException("用户名不存在！！"));
    return courseService.getNoSubscribed(user.getId(), coursePage, course);
  }

  /** 课程订阅 */
  @PostMapping("order/{courseId}")
  public void order(Principal principal, @PathVariable("courseId") Long courseId) {
    User user =
        Optional.ofNullable(userService.loadUserByUserName(principal.getName()))
            .orElseThrow(() -> new UsernameNotFoundException("用户名不存在！！"));
    CourseOrder courseOrder = new CourseOrder();
    courseOrder.setCourseId(courseId);
    courseOrder.setStudentId(user.getId());
    courseOrderService.save(courseOrder);
  }

  /** 取消课程订阅 */
  @DeleteMapping("order/{courseId}")
  public void unOrder(Principal principal, @PathVariable("courseId") Long courseId) {
    User user =
        Optional.ofNullable(userService.loadUserByUserName(principal.getName()))
            .orElseThrow(() -> new UsernameNotFoundException("用户名不存在！！"));
    CourseOrder courseOrder = new CourseOrder();
    courseOrderService.remove(
        new LambdaQueryWrapper<CourseOrder>()
            .eq(CourseOrder::getCourseId, courseId)
            .eq(CourseOrder::getStudentId, user.getId()));
  }

  /**
   * 查询老师的所有课程
   */
  @GetMapping("/teacher")
  public  List<Course> getTeacherCourses(Principal principal){
    final User user = userService.loadUserByUserName(principal.getName());
    return courseService.list(new LambdaQueryWrapper<Course>().eq(Course::getTeacherId,user.getId()));
  }
}
